package com.mia.props.events;

import com.mia.props.Props;
import com.mia.props.common.TileFake;
import com.mia.props.common.TileProps;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action;

public enum DecoEventHandler {
   INSTANCE;

   public static void register() {
      MinecraftForge.EVENT_BUS.register(INSTANCE);
      FMLCommonHandler.instance().bus().register(INSTANCE);
   }

   @SubscribeEvent
   public void onLivingDrops(LivingDropsEvent event) {
      if (Props.clayDrops && event.entity.worldObj.rand.nextInt(2) == 0) {
         ItemStack stack = new ItemStack(Props.itemClay, 1, event.entity.worldObj.rand.nextInt(3));
         event.drops.add(new EntityItem(event.entity.worldObj, event.entity.posX, event.entity.posY, event.entity.posZ, stack));
      }

   }

   @SubscribeEvent
   public void onPlayerInteractEvent(PlayerInteractEvent event) {
      if (!event.world.isRemote) {
         if (!event.entityPlayer.capabilities.isCreativeMode) {
            if (event.action != Action.RIGHT_CLICK_AIR) {
               ItemStack held = event.entityPlayer.getCurrentEquippedItem();
               if (held != null && held.getItem().equals(Props.itemTool)) {
                  TileEntity te = Props.getTileEntityPreferNotCreating(event.world, event.x, event.y, event.z);
                  if (te instanceof TileProps || te instanceof TileFake) {
                     TileProps prop = te instanceof TileFake ? ((TileFake)te).getMaster() : (TileProps)te;
                     if (prop != null && Props.instance.modelDataVariantsList.containsKey(prop.type)) {
                        prop.type = event.action == Action.LEFT_CLICK_BLOCK ? ((Props.MetaVariantListNode)Props.instance.modelDataVariantsList.get(prop.type)).nextID : ((Props.MetaVariantListNode)Props.instance.modelDataVariantsList.get(prop.type)).prevID;
                        prop.markDirty();
                        event.world.markBlockForUpdate(event.x, event.y, event.z);
                        held.damageItem(1, event.entityPlayer);
                        if (held.stackSize == 0) {
                           event.entityPlayer.destroyCurrentEquippedItem();
                        }

                        event.setCanceled(true);
                     }
                  }
               }
            }

         }
      }
   }
}
